/**
 * 
 */
package org.tinygroup.bizframe.basedao;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;
import org.tinygroup.sequence.impl.MultipleSequenceDao;
import org.tinygroup.sequence.impl.MultipleSequenceFactory;

/**
 * @author Paul
 *
 */
public class MultiSequenceProcessor {
     
	private static final Logger LOGGER = LoggerFactory.getLogger(MultiSequenceProcessor.class);
	
	private MultipleSequenceFactory sequenceFactory=new MultipleSequenceFactory();
	public void init(Map<String,DataSource> dataSources){
		
		MultipleSequenceDao multipleSequenceDao=new MultipleSequenceDao();
		Iterator<String> itr = dataSources.keySet().iterator();
		List<DataSource> lsDS = new ArrayList<DataSource>();
		while(itr.hasNext()){
			String key = itr.next();
			DataSource ds = dataSources.get(key);
			try{
				Connection conn = ds.getConnection();
//				String sqlSchema = "CREATE SCHEMA IF NOT EXISTS `db_"+key+"`;";
				String sqlTable ="CREATE TABLE IF NOT EXISTS `sequence` (`name` VARCHAR(50) NOT NULL, `value` BIGINT NOT NULL, `min_value` BIGINT NOT NULL,`max_value` BIGINT NOT NULL,`step` INT NOT NULL, `gmt_create` DATE NULL,`gmt_modified` DATE NULL)";
				Statement stat = conn.createStatement();
//				stat.execute(sqlSchema);
				boolean success= stat.execute(sqlTable);
				LOGGER.logMessage(LogLevel.WARN, "分布式主键数据库表创建{0}",success);
				stat.close();
				conn.close();
				lsDS.add(ds);
			}
			catch(SQLException e){
				LOGGER.logMessage(LogLevel.ERROR, "创建分布式数据库表失败", e);
			}
			
		}
		if(lsDS.isEmpty()){
			LOGGER.logMessage(LogLevel.WARN, "分布式主键数据库配置无效");
			return;
		}
		multipleSequenceDao.setDataSourceList(lsDS);//dataSources，你自己的dataSource列表,(类型：List<DataSource>)
		sequenceFactory.setMultipleSequenceDao(multipleSequenceDao);
		sequenceFactory.init();
		
	}
	
	public Long nextKey(String seqName) throws Exception{
		return sequenceFactory.getNextValue(seqName);
	}
}
